package com.epsoft.odin7cj.flow.example;

import java.util.List;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

public class AMainTest {

	public static void main1(String[] args) throws Exception {
		// 流程引擎
		ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
		// 获取存储服务
		RepositoryService repoService = engine.getRepositoryService();
		// 获取运行服务
		RuntimeService runService = engine.getRuntimeService();
		// 获取任务服务
		TaskService taskService = engine.getTaskService();
		
		AMainTest mainTest = new AMainTest();
		
		// 部署
//		mainTest.deployBpmnConfig(repoService); 
		
		/**
		// 查询发布的流程定义
		ProcessDefinition proDef = mainTest.selectProcessDefinition(repoService, "main-test-key");
		System.out.println("\n 查询key为  main-test-key 流程定义：\n  流程定义ID："+proDef.getId()+" ,流程定义名称："+proDef.getName());
		
		// 启动流程实例
		 mainTest.startProcess(runService, proDef);
		
		// 获取任务列表
		List<Task> taskList = mainTest.getTask(runService, taskService, proDef);
		for(Task tmpTask : taskList) {
			System.out.println("\n 获取任务：\n"+
					"任务id: " +tmpTask.getTaskDefinitionKey() + 
					",任务名称: " +tmpTask.getName() +
					",流程实例ID： " + tmpTask.getProcessInstanceId()
					);
		}
		*/
	}
	
	// 发布流程
	void deployBpmnConfig(RepositoryService rs) {
		try {
			DeploymentBuilder builder = rs.createDeployment(); 
			builder.name("稽核检查流程");
			builder.addClasspathResource("bpmn/a-main-test.bpmn");
			builder.deploy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// 选择流程定义
	ProcessDefinition selectProcessDefinition(RepositoryService rs,String processDefKey) {
		List<Deployment> listDeployment = rs.createDeploymentQuery().list();
		for(Deployment deployment : listDeployment) {
			ProcessDefinition prodef = rs.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
			if(processDefKey.equals(prodef.getKey())) {
				return prodef;
			}
		}
		return null;
	} 
	
	// 启动流程
	ProcessInstance startProcess(RuntimeService runService,ProcessDefinition proDef) {
		ProcessInstance pi = runService.startProcessInstanceById(proDef.getId());
		return pi;
	}
	
	// 获取任务
	List<Task> getTask(RuntimeService runService,TaskService taskService,ProcessDefinition proDef) {
		ProcessInstance pi = runService.createProcessInstanceQuery().processDefinitionId(proDef.getId()).singleResult();
		System.out.println("\n 获取流程实例：\n"+" 流程实例ID："+pi.getId() + "，流程定义ID" +pi.getProcessDefinitionId());
		List<Task> taskList = taskService.createTaskQuery().processInstanceId(pi.getId()).list();
		
		
		return taskList;
		
	}
}
